let
Keyword in JavaScriptThe let
keyword is used to declare variables in JavaScript with block scope. It was introduced in ES6 (ECMAScript 2015) as an improvement over var
.
let
Block Scope (Limited to {}
blocks)
var
, let
is confined to the block where it is declared.
✅ let
is not accessible outside the block.
No Hoisting (Cannot be used before declaration)
let
is hoisted, but not initialized, meaning you cannot use it before declaring.
Allows Reassignment (Unlike const
)
Does Not Allow Redeclaration in the Same Scope
var
, let
does not allow redeclaration within the same scope.
var
, let
, and const
Feature | var | let | const |
---|---|---|---|
Scope | Function-scoped | Block-scoped | Block-scoped |
Hoisting | Hoisted & initialized (undefined ) | Hoisted but not initialized | Hoisted but not initialized |
Redeclaration | Allowed | ❌ Not allowed | ❌ Not allowed |
Reassignment | ✅ Allowed | ✅ Allowed | ❌ Not allowed |
let
?✅ When you need a mutable variable (a variable that can change).
✅ When you need block scope to avoid unintended behavior.
✅ When const
is too restrictive (you must reassign the value).
Would you like more examples or explanations? 🚀